<?php
/**
 * Created by b17
 * 3/22/12 6:58 PM
 */

namespace Managers\Builder;

use \Lib\ResLoader,
Doctrine\ORM\QueryBuilder;

abstract class GenericBuilder
{
    /**
     * @var QueryBuilder
     */
    protected $_qb;

    private $_limit = null;
    private $_offset = null;

    private $_dateFormat = 'm/d/Y';

    public function __construct()
    {
        $this->_qb = $this->_getQueryBuilder();
    }

    /**
     * @return QueryBuilder
     */
    protected function _getQueryBuilder()
    {
        $qb = ResLoader::getResource('Doctrine')->getEntityManager()->createQueryBuilder();
        return $qb;
    }

    public function setLimit($limit, $offset = 0)
    {
        $this->_limit = $limit;
        $this->_offset = $offset;
    }

    protected function _applyLimits(QueryBuilder $qb)
    {
        if ($this->_limit) {
            $qb->setMaxResults($this->_limit);
        }

        if ($this->_offset) {
            $qb->setFirstResult($this->_offset);
        }
    }

    public function getArrayResult()
    {
        $qb = clone $this->_qb;
        $this->_applyLimits($qb);
        return $qb->getQuery()->getArrayResult();
    }

    public function getResult()
    {
        $qb = clone $this->_qb;
        $this->_applyLimits($qb);
        return $qb->getQuery()->getArrayResult();
    }

    public function getOne()
    {
        $res = $this->_qb->getQuery()->getArrayResult();
        return count($res) ? $res[0] : false;
    }

    public function getOneEntity()
    {
        $res = $this->_qb->getQuery()->getResult();
        return count($res) ? $res[0] : false;

    }

    protected function _createDateTime($timeString)
    {
        return \DateTime::createFromFormat($this->_dateFormat, $timeString);
    }

    public function setDateFormat($dateFormat)
    {
        $this->_dateFormat = $dateFormat;
    }

    public function getDateFormat()
    {
        return $this->_dateFormat;
    }

    /**
     * Возвращает количество записей.
     *
     * @param string $alias alias главной таблицы.
     * @return mixed
     */
    public function getTotal($alias)
    {
        $qb = clone $this->_qb;
        $qb->select("count({$alias}.id) as total");
        $res = $qb->getQuery()->getArrayResult();
        return $res[0]['total'];
    }
}
